import 'dart:async';
import 'dart:ui';
import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:amap_flutter_location/amap_location_option.dart';
import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';

//  测试版
// 82:2A:7B:4F:18:0D:59:9D:D1:A9:52:74:A6:B1:83:9E:BB:8D:D7:5A
//  开发板
// 23:3B:E5:46:AF:29:34:DC:DB:2E:66:BF:B9:0C:D9:47:08:62:91:F9

class AmapPage extends StatefulWidget {
  const AmapPage({Key? key}) : super(key: key);

  @override
  State<AmapPage> createState() => _AmapPageState();
}

class _AmapPageState extends State<AmapPage> {
  var address = ""; //地址

  var longitude = ""; //经度

  var latitude = ""; // 纬度

  StreamSubscription<Map<String, Object>>? _locationListener;

  AMapFlutterLocation _locationPlugin = new AMapFlutterLocation();

  requestPermiss() async {
    Map<Permission, PermissionStatus> statuses = await [
      Permission.location,
      // Permission.storage,
      // Permission.camera,
    ].request();
    //验证权限是否授权
    var status = await Permission.location.status;

    if (status == PermissionStatus.granted) {
      //LogUtil.d('定位权限：true');
      print("true");
      //已经授权
    } else {
      //LogUtil.d('定位权限：false');
      print("false");
      //退出应用
      Future.value(true);
    }
  }

  //

  // SHA1: 87:EB:12:5B:2F:4C:96:A6:29:8D:AC:2B:DB:59:24:26:44:EB:D2:7A
  // SHA256: 5B:85:61:78:0F:31:2C:48:22:C6:53:87:F8:77:81:9C:A0:67:10:5A:7F:81:9E:AE:71:9C:6D:66:18:A3:29:94
  // 签名算法名称: SHA1withRSA
  // 主体公共密钥算法: 2048 位 RSA 密钥
  // 版本: 1

  /*地
113.910599
22.484500
图定位*/
  void initLocation() {
    //高德定位
    AMapFlutterLocation.updatePrivacyShow(true, true);
    AMapFlutterLocation.updatePrivacyAgree(true);
    //AMapLocationClient.updatePrivacyShow(getApplicationContext(),true,true);
    //AMapLocationClient.updatePrivacyAgree(getApplicationContext(),true);
    AMapFlutterLocation.setApiKey(
        "73dc317558911fceb34c71276ed44883", "73dc317558911fceb34c71276ed44883");

    ///iOS 获取native精度类型
    //if (Platform.isIOS) {
    //requestAccuracyAuthorization();
    //}
    ///注册定位结果监听
    _locationListener = _locationPlugin
        .onLocationChanged()
        .listen((Map<String, Object> result) {
      setState(() {
        //_locationResult = result;
        print("高德定位===========" + result.toString());
        print("高德定位latitude===========" + result['latitude'].toString());
        print("高德定位longitude: ===========" + result['longitude'].toString());
        print("高德定位country: ===========" + result['country'].toString());
        print("高德定位province: ===========" + result['province'].toString());
        print("高德定位city: ===========" + result['city'].toString());
        print("高德定位city: ===========" + result['city'].toString());
        print("高德定位district: ===========" + result['district'].toString());
        print("高德定位adCode: ===========" + result['adCode'].toString());
        address =
            result['address'].toString() + result['description'].toString();
        longitude = result['longitude'].toString();
        latitude = result['latitude'].toString();
      });
    });
    _setLocationOption();
  }

  ///设置定位参数
  void _setLocationOption() {
    if (null != _locationPlugin) {
      AMapLocationOption locationOption = new AMapLocationOption();

      ///是否单次定位
      locationOption.onceLocation = false;

      ///是否需要返回逆地理信息
      locationOption.needAddress = true;

      ///逆地理信息的语言类型
      locationOption.geoLanguage = GeoLanguage.DEFAULT;
      locationOption.desiredLocationAccuracyAuthorizationMode =
          AMapLocationAccuracyAuthorizationMode.ReduceAccuracy;
      locationOption.fullAccuracyPurposeKey = "AMapLocationScene";

      ///设置Android端连续定位的定位间隔
      locationOption.locationInterval = 20000;

      ///设置Android端的定位模式<br>
      ///可选值：<br>
      ///<li>[AMapLocationMode.Battery_Saving]</li>
      ///<li>[AMapLocationMode.Device_Sensors]</li>
      ///<li>[AMapLocationMode.Hight_Accuracy]</li>
      locationOption.locationMode = AMapLocationMode.Hight_Accuracy;

      ///设置iOS端的定位最小更新距离<br>
      locationOption.distanceFilter = -1;

      ///设置iOS端期望的定位精度
      /// 可选值：<br>
      /// <li>[DesiredAccuracy.Best] 最高精度</li>
      /// <li>[DesiredAccuracy.BestForNavigation] 适用于导航场景的高精度 </li>
      /// <li>[DesiredAccuracy.NearestTenMeters] 10米 </li>
      /// <li>[DesiredAccuracy.Kilometer] 1000米</li>
      /// <li>[DesiredAccuracy.ThreeKilometers] 3000米</li>
      locationOption.desiredAccuracy = DesiredAccuracy.Best;

      ///设置iOS端是否允许系统暂停定位
      locationOption.pausesLocationUpdatesAutomatically = false;

      ///将定位参数设置给定位插件
      _locationPlugin.setLocationOption(locationOption);

      ///开始定位
      _startLocation();
    }
  }

  ///获取iOS native的accuracyAuthorization类型
  void requestAccuracyAuthorization() async {
    AMapAccuracyAuthorization currentAccuracyAuthorization =
        await _locationPlugin.getSystemAccuracyAuthorization();
    if (currentAccuracyAuthorization ==
        AMapAccuracyAuthorization.AMapAccuracyAuthorizationFullAccuracy) {
      print("精确定位类型");
    } else if (currentAccuracyAuthorization ==
        AMapAccuracyAuthorization.AMapAccuracyAuthorizationReducedAccuracy) {
      print("模糊定位类型");
    } else {
      print("未知定位类型");
    }
  }

  ///开始定位
  void _startLocation() {
    if (null != _locationPlugin) {
      _locationPlugin.startLocation();
    }
  }

  ///停止定位
  void _stopLocation() {
    if (null != _locationPlugin) {
      _locationPlugin.stopLocation();
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //start();
  }

  //开启定位
  void start() {
    requestPermission();
    initLocation();
  }

  /// 动态申请定位权限
  void requestPermission() async {
    // 申请权限
    bool hasLocationPermission = await requestLocationPermission();
    if (hasLocationPermission) {
      print("定位权限申请通过");
    } else {
      print("定位权限申请不通过");
    }
  }

  /// 申请定位权限
  /// 授予定位权限返回true， 否则返回false
  Future<bool> requestLocationPermission() async {
    //获取当前的权限
    var status = await Permission.location.status;
    if (status == PermissionStatus.granted) {
      //已经授权
      return true;
    } else {
      //未授权则发起一次申请
      status = await Permission.location.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    //移除定位监听
    if (null != _locationListener) {
      _locationListener!.cancel();
    }

    ///销毁定位
    if (null != _locationPlugin) {
      _locationPlugin.destroy();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("定位"),
          centerTitle: true,
        ),
        body: Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          child: Padding(
            padding: EdgeInsets.all(15),
            child: Center(
              child: ListView(
                children: [
                  Container(
                    child: Text("详细地址"),
                  ),
                  SizedBox(
                    height: 6,
                  ),
                  Container(
                    child: Text(address),
                  ),
                  SizedBox(
                    height: 20,
                  ),
                  Container(
                    child: Text("经度"),
                  ),
                  SizedBox(
                    height: 6,
                  ),
                  Container(
                    child: Text(longitude),
                  ),
                  SizedBox(
                    height: 20,
                  ),
                  Container(
                    child: Text("纬度"),
                  ),
                  SizedBox(
                    height: 6,
                  ),
                  Container(
                    child: Text(latitude),
                  ),
                  SizedBox(
                    height: 70,
                  ),
                  InkWell(
                    onTap: () {
                      start(); //开启定位
                    },
                    child: Padding(
                      padding: EdgeInsets.only(left: 80,right: 80),
                      child: Container(
                        height: 60,
                        width: 50,
                        decoration: BoxDecoration(
                            color: Colors.blue, borderRadius: BorderRadius.circular(20)),
                        child: Center(
                            child: Text("开始定位",style: TextStyle(fontSize: 22,color: Colors.orangeAccent),),

                        ),
                      ),
                    ),
                  ),


                ],
              ),
            ),
          ),
        ));
  }
}
